using System;

namespace Common.Core.Objects
{
	public static class DefaultPropertyValueHelper
	{
		public static void ApplyDefaultValues( object target )
		{
			Guard.IsNotNull( target, "target" );

			var type = target.GetType();
			foreach ( var attribute in type.GetAttributes<DefaultPropertyValueAttributeBase>() )
			{
				var info = type.GetProperty( attribute.PropertyName );
				if ( info != null )
				{
					object value = attribute.GetValue( info ),
					       current = info.GetValue( target, null );
					if ( !Equals( current, value ) )
					{
						info.SetValue( target, value, null );
					}
					continue;
				}
				throw new InvalidOperationException( string.Format( "Could not find the property name '{0}' on type '{1}'.", attribute.PropertyName, type.FullName ) );
			}
		}
	}
}